/**
 * 定义表单itfreerForm.core模块
 */
(function(window, angular, undefined){
	/**
	* 定义WDP模块
	*/
	var wdp = angular.module('water.apps.WasteGas.wdp');

	wdp.filter('percent',function($filter){
	    return function(num,p1){
	        var r = num*100;
	        if(p1){
	        	r = $filter('number')(r,p1);
	        }else{
	        	r = $filter('number')(r);
	        }
	        r = Math.round(r*100) / 100;
	        return r+"%";
	    }
	});
	
	wdp.filter('toYearMonth',function(){
	    return function(num){
	    	var number = parseInt(num);
	        if(isNaN(number)) return '';
	        var y = parseInt(number/12);
	        var m = number%12;
	        var r = "";
	        if(y>0)
	        	r+=y+"年";
	        if(m>0){
	        	r+=m+"个月";
	        }
	        return r;
	    }
	});
	
	wdp.filter('dataStatus',function(){
	    return function(status){
	        var r = "有效";
	        if(status=='1')
	        	r= "异常";
	        else if(status=='2')
	        	r = "超标";
	        else if(status=='3')
	        	r = "缺失";
	        return r;
	    }
	});
	
	wdp.filter('dataStatus',function(){
	    return function(status){
	        var r = "";
	        if(status=='0')
	        	r= "有效";
	        else if(status=='1')
	        	r = "超标";
	        else if(status=='2')
	        	r = "异常";
	        else if(status=='3')
	        	r = "缺失";
	        return r;
	    }
	});
	
	wdp.filter('dataFrom',function(){
	    return function(from){
	        var r = "";
	        if(from=='0')
	        	r= "直出数据";
	        else if(from=='1')
	        	r = "人工监测";
	        else if(from=='2' || from=='3')
	        	r = "人工修约";
	        else if(from=='4' || from =='5')
	        	r = "系统修约";
	        return r;
	    }
	});
	
	wdp.directive('isOver',function(){
	        return {
	            restrict: 'A',
	            scope: {
	                over: '=isOver'
	            },
	            link:function(scope, elm, attr){
	                if(scope.$parent.$last){
	                    scope.over = true;
	                }
	            }
	        }
	    });
	
	/**
	 * 定义特定交互下的特定方法
	 */
	wdp.factory('$wdp', function($rootScope, $http,$gisObject) {
		$wdp = {
			isFullScreen : false,
			fullScreenTitle:{title:'全屏'},

			/**
			 * windows窗口大小改变事件监听
			 */
			addWindowResizeListener : function(){
				var resizeTimer = null;
				$(window).resize(function(){
					//添加时间懒加载 修复IE9以下重复多次resize事件问题
					if (resizeTimer) clearTimeout(resizeTimer);
					resizeTimer = setTimeout(function() {
						$wdp.widowResizeEventHandler();
					}, 200);
				});
			},

			/**
			 * Windows窗口变化时处理事件,同步更改地图大小
			 * @return {[type]} [description]
			 */
			widowResizeEventHandler : function () {
				var Window_H = $(window).height();
				var Window_W = $(window).width();
				var Map_H , Map_W;
				var _widthOff;
				
				if(typeof widthOff != "undefined" && widthOff != null && widthOff != 0 && widthOff != ""){
					_widthOff = widthOff;
				}
				else{
					_widthOff = 324;
				}
				
				if($wdp.isFullScreen){
					Map_H = Window_H;
				}else{
					Map_H = Window_H - 105;
				}
				if(window.isWisthFull){
					Map_W = Window_W;
				}else{
					Map_W = Window_W - _widthOff;
				}
				Map_H = Map_H - 50;
				this.Map_H = Map_H;
				this.Map_W = Map_W;
				window.Map_H = Map_H;
				window.Map_W = Map_W;
				$rootScope.Map_H = Map_H;
				$rootScope.Map_W = Map_W;
				$rootScope.widthOff = _widthOff;
				if(Window_W < 1200){
					Map_W = 1200 - _widthOff;
				}
				$("div#zs_gis").css({
					height : Map_H + "px",
					width : Map_W + "px"
				});
				$("#mapLoading").css({
					height : Map_H + "px",
					width : Map_W + "px",
					lineHeight:Map_H + "px"
				});
				$("div#arcMap").css({
					height : Map_H + "px",
					width : Map_W + "px"
				});
				$("div[ui-view='model']").css({
					height : Map_H + "px"
				});
				$("div#arcMap").find('.container').css({
					height : Map_H + "px",
					width : Map_W + "px"
				});
				// 地图同步刷新
				$rootScope.reflashMap();
			},

			/**
			 * 全屏控制
			 */
			fullScreen : function() {
				$wdp.isFullScreen = !$wdp.isFullScreen;
				window.isFullScreen = $wdp.isFullScreen;
				$wdp.fullScreenTitle.title=($wdp.isFullScreen?'退出全屏':'全屏');
				$wdp.widowResizeEventHandler();
			}
		};
		for(f in $wdp){
			$rootScope[f] = $wdp[f];
		}
		return $wdp;
	});

	/**
	* 路由配置
	*/
	wdp.config(function ($stateProvider, $urlRouterProvider) {
		var sessionId = $("#_sessionid").html();
		$stateProvider.state('StationMap',{
			views: {
				'nav': {
					controller : 'gisFirstRouterCtrl',
					template: ''
				},
				'model': {
					module:'water.apps.WasteGas.stationMap.stationMapManager',
					controller : 'stationMapManagerController',
					templateUrl: getBasePath()+'/WasteGas/stationMap/leftStationList.do?sessionId='+sessionId
				},
				'panel': {
					templateUrl: getBasePath()+'/common/command/blank.do'
				}				
			}
		});
		
		//工业污染源-废气，企业信息管理
		$stateProvider.state('gyfqQyManager',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					template: ''
				},
				'model': {
					controller : 'PolluteSourceController',
					templateUrl: getBasePath()+'/WasteGas/companyInfo/WasteGasPanel.do' 
				},
				'panel': {
					controller:'OperationManagerNavController',
					templateUrl: getBasePath()+'/WasteGas/gyfqQyManager/GyfqQyInfoMain.do'
				}
			}
		})
		.state('gyfqQyManager.gyfqInfo',{
			controller : 'OperationManagerNavController',
			templateUrl: getBasePath()+'/WasteGas/gyfqQyManager/gyfqInfo/navMain.do'
		})
		.state('gyfqQyManager.gyfqInfo.info',{
			module:"water.apps.WasteGas.gyfqQyManager.gyfqInfo.PsWwtpAttrManager", 
			controller:"GyfqManagerPsWwtpAttrManagerController",
			url:'/gyfqQyManager.gyfqInfo.info',
			templateUrl: getBasePath()+'/WasteGas/gyfqQyManager/gyfqInfo/psWwtpAttr/list.do'
		})
		.state('gyfqQyManager.gyfqInfo.monitorStation',{
			url:'/gyfqQyManager.gyfqInfo.monitorStation',
			module:'water.apps.WasteGas.gyfqQyManager.gyfqInfo.monitorStationManager',
			controller:'fqStationManagerController',
			templateUrl: getBasePath()+'/WasteGas/gyfqQyManager/gyfqInfo/monitorStation/list.do'
		})
		.state('gyfqQyManager.gyfqInfo.dataCollectionInstrumet',{
			url:'/gyfqQyManager.gyfqInfo.dataCollectionInstrumet',
			module:'water.apps.WasteGas.gyfqQyManager.gyfqInfo.dataCollectionInstrumetManager',
			controller:'fqdataCollectionInstrumetManagerController',
			templateUrl: getBasePath()+'/WasteGas/gyfqQyManager/gyfqInfo/dataCollectionInstrumet/list.do'
		})
		.state('gyfqQyManager.gyfqInfo.monitorEquipment',{
			url:'/gyfqQyManager.gyfqInfo.monitorEquipment',
			module:'water.apps.WasteGas.gyfqQyManager.gyfqInfo.monitorEquipmentManager',
			controller:'fqmonitorEquipmentManagerController',
			templateUrl: getBasePath()+'/WasteGas/gyfqQyManager/gyfqInfo/monitorEquipment/list.do'
		})
		.state('gyfqQyManager.gyfqInfo.sitePollutants',{
			url:'/gyfqQyManager.gyfqInfo.sitePollutants',
			module:'water.apps.WasteGas.gyfqQyManager.gyfqInfo.sitePollutantsManager',
			controller:'fqSitePollutantsManagerController',
			templateUrl: getBasePath()+'/WasteGas/gyfqQyManager/gyfqInfo/sitePollutants/list.do'
		})
		.state('gyfqQyManager.gyfqInfo.deviceAccept',{
			url:'/gyfqQyManager.gyfqInfo.deviceAccept',
			module:'water.apps.WasteGas.gyfqQyManager.gyfqInfo.deviceAcceptManager',
			controller:'fqDeviceAcceptController',
			templateUrl: getBasePath()+'/WasteGas/gyfqQyManager/gyfqInfo/deviceAccept/list.do'
		})
		.state('gyfqQyManager.fqAssetsRegister',{
			url:'/gyfqQyManager.fqAssetsRegister',
			controller: 'fqAssetsRegisterManager',
			module:'water.apps.WasteGas.gyfqQyManager.assetsRegister.assetsRegisterManager',
			templateUrl: getBasePath()+'/WasteGas/gyfqQyManager/assetsRegister/list.do?sessionId='+sessionId
		});
		//报表：包括实时数据，历史数据，基础报表
		$stateProvider.state('Report',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					template: ''
				},
				'model': {
					controller : 'StationListController',
					templateUrl: getBasePath()+'/WasteGas/ReportData/ReportSearchList_singleStation.do'
				},
				'panel': {
					controller:'OperationManagerNavController',
					templateUrl: getBasePath()+'/WasteGas/reportRealtime/DataReportMain.do'
				}
			}
		})
		//实时数据
		.state('Report.RealTimeReport',{
			controller : 'reportRealTimeManagerController',
			templateUrl: getBasePath()+'/WasteGas/reportRealtime/realTime.do'
		})
		.state('Report.history',{
			controller : 'reportHistoryNavController',
			module:'water.apps.WasteGas.reportHistory.reportHistoryNav',
			templateUrl: getBasePath()+'/WasteGas/reportHistory/navMain.do?sessionId='+sessionId
		})
		.state('Report.history.minuteReport',{
			url:'/Report.history.minuteReport',
			controller : 'reportMinDataManagerController',
			module:'water.apps.WasteGas.reportHistory.reportMinDataManager',
			templateUrl: getBasePath()+'/WasteGas/reportHistory/minute.do?sessionId='+sessionId
		})
		.state('Report.history.hourReport',{
			url:'/Report.history.hourReport',
			controller : 'reportHourDataManagerController',
			module:'water.apps.WasteGas.reportHistory.reportHourDataManager',
			templateUrl: getBasePath()+'/WasteGas/reportHistory/hour.do?sessionId='+sessionId
		})
		.state('Report.history.dayReport',{
			url:'/Report.history.dayReport',
			controller : 'reportDayDataManagerController',
			module:'water.apps.WasteGas.reportHistory.reportDayDataManager',
			templateUrl: getBasePath()+'/WasteGas/reportHistory/day.do?sessionId='+sessionId
		})
		//数据审核、查询页面
		.state('Report.history.dataAudit',{
			params:{curRow:null},
			url:'/Report.history.dataAudit',
			controller : 'reportDataAuditManagerController',
			module:'water.apps.WasteGas.reportHistory.reportDataAuditManager',
			templateUrl: getBasePath()+'/WasteGas/reportHistory/dataAudit.do?sessionId='+sessionId
		})
		//数据审核、审核页面
		.state('Report.history.dataAuditDetail',{
			params:{curRow:null},
			url:'/Report.history.dataAuditDetail',
			controller : 'reportDataAuditDetailManagerController',
			module:'water.apps.WasteGas.reportHistory.reportDataAuditDetailManager',
			templateUrl: getBasePath()+'/WasteGas/reportHistory/dataAuditDetail.do?sessionId='+sessionId
		})
		//数据报表
		.state('Report.ReportTotal',{
			controller : 'reportDataNavController', //ReportController  
			module:'water.apps.WasteGas.ReportData.reportDataNav',
			templateUrl: getBasePath()+'/WasteGas/ReportData/navMain.do'
		})
		//数据报表均值统计
		.state('Report.ReportTotal.avgStatisticsReport',{
			url:'/Report.ReportTotal.avgStatisticsReport',
			controller : 'reportAverageStatisticsNAVController',
			module:'water.apps.WasteGas.ReportData.avgStatistics.avgStatisticsNAV',
			templateUrl: getBasePath()+'/WasteGas/ReportData/avgStatistics/navMain.do?sessionId='+sessionId
		})
		.state('Report.ReportTotal.avgStatisticsReport.minute',{
			url:'/Report.ReportTotal.avgStatisticsReport.minute',
			controller : 'reportAvgStatisticsMinuteController',
			module:'water.apps.WasteGas.ReportData.avgStatistics.minDataManager',
			templateUrl: getBasePath()+'/WasteGas/ReportData/avgStatistics/minute.do?sessionId='+sessionId
		})
		.state('Report.ReportTotal.avgStatisticsReport.hour',{
			url:'/Report.ReportTotal.avgStatisticsReport.hour',
			controller : 'reportAvgStatisticsHourController',
			module:'water.apps.WasteGas.ReportData.avgStatistics.hourDataManager',
			templateUrl: getBasePath()+'/WasteGas/ReportData/avgStatistics/hour.do?sessionId='+sessionId
		})
		.state('Report.ReportTotal.avgStatisticsReport.day',{
			url:'/Report.ReportTotal.avgStatisticsReport.day',
			controller : 'reportAvgStatisticsDayController',
			module:'water.apps.WasteGas.ReportData.avgStatistics.dayDataManager',
			templateUrl: getBasePath()+'/WasteGas/ReportData/avgStatistics/day.do?sessionId='+sessionId
		})
		.state('Report.ReportTotal.avgStatisticsReport.week',{
			url:'/Report.ReportTotal.avgStatisticsReport.week',
			controller : 'reportAvgStatisticsWeekController',
			module:'water.apps.WasteGas.ReportData.avgStatistics.weekDataManager',
			templateUrl: getBasePath()+'/WasteGas/ReportData/avgStatistics/week.do?sessionId='+sessionId
		})
		.state('Report.ReportTotal.avgStatisticsReport.month',{
			url:'/Report.ReportTotal.avgStatisticsReport.month',
			controller : 'reportAvgStatisticsMonthController',
			module:'water.apps.WasteGas.ReportData.avgStatistics.monthDataManager',
			templateUrl: getBasePath()+'/WasteGas/ReportData/avgStatistics/month.do?sessionId='+sessionId
		})
		.state('Report.ReportTotal.avgStatisticsReport.quarter',{
			url:'/Report.ReportTotal.avgStatisticsReport.quarter',
			controller : 'reportAvgStatisticsQuarterController',
			module:'water.apps.WasteGas.ReportData.avgStatistics.quarterDataManager',
			templateUrl: getBasePath()+'/WasteGas/ReportData/avgStatistics/quarter.do?sessionId='+sessionId
		})
		.state('Report.ReportTotal.avgStatisticsReport.year',{
			url:'/Report.ReportTotal.avgStatisticsReport.year',
			controller : 'reportAvgStatisticsYearController',
			module:'water.apps.WasteGas.ReportData.avgStatistics.yearDataManager',
			templateUrl: getBasePath()+'/WasteGas/ReportData/avgStatistics/year.do?sessionId='+sessionId
		})
		//数据烟排量统计
		.state('Report.ReportTotal.displaceStatisticsReport',{
			url:'/Report.ReportTotal.displaceStatisticsReport',
			controller : 'displaceStatisticsNAVController',
			module:'water.apps.WasteGas.ReportData.displaceStatistics.displaceStatisticsNAV',
			templateUrl: getBasePath()+'/WasteGas/ReportData/displaceStatistics/navMain.do?sessionId='+sessionId
		})
		.state('Report.ReportTotal.displaceStatisticsReport.month',{
			url:'/Report.ReportTotal.displaceStatisticsReport.month',
			controller : 'displaceStatisticsMonthController',
			module:'water.apps.WasteGas.ReportData.displaceStatistics.monthDataManager',
			templateUrl: getBasePath()+'/WasteGas/ReportData/displaceStatistics/month.do?sessionId='+sessionId
		})/*;
		
		$stateProvider.state('modify',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					template:''
				},
				'model': {
					templateUrl: getBasePath()+'/WasteGas/ReportData/ReportSearchList_singleStation.do?sessionId='+sessionId
				},
				'panel': {
					templateUrl: getBasePath()+'/WasteGas/dataModification/Main.do?sessionId='+sessionId
				}
			}
		})*/.state('Report.modifydata',{
			module:'water.apps.WasteGas.dataModification.dataModificationManager',
			controller: 'ModifyDataController',
			templateUrl: getBasePath()+'/WasteGas/dataModification/DataModification.do?sessionId='+sessionId
		}).state('Report.certificateMgr',{
			module:'water.apps.WasteGas.dataModification.modifyCertificateManager',
			controller: 'ModifyCertificateMgrController',
			templateUrl: getBasePath()+'/WasteGas/dataModification/CertificateMgr.do?sessionId='+sessionId
		}).state('Report.connection',{
			module:'water.apps.WasteGas.dataModification.connectionCertificateManager',
			controller: 'ConnectionCertificateManager',
			templateUrl: getBasePath()+'/WasteGas/dataModification/ConnectionCertificate.do?sessionId='+sessionId
		});
		
		
		//行政区统计报表
		$stateProvider.state('ReportXZQ',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					template: ''
				},
				'model': {
					controller : 'XZQReportSearchController',
					templateUrl: getBasePath()+'/common/ReportData/XZQSearch.do'
				},
				'panel': {
					templateUrl: getBasePath()+'/common/ReportData/ReportDataMain.do'
				}
			}
		}).state('ReportXZQ.statistics',{
			templateUrl: getBasePath()+'/common/ReportData/ReportStatisticsXZQ.do'
		}).state('ReportXZQ.statistics.monthReport',{
			controller : 'XZQMonthReportController',
			templateUrl: getBasePath()+'/sw/ReportData/ReportMonthXZQ.do'
		}).state('ReportXZQ.statistics.quarterReport',{
			controller : 'XZQQuarterReportController',
			templateUrl: getBasePath()+'/sw/ReportData/ReportQuarterXZQ.do'
		}).state('ReportXZQ.statistics.yearReport',{
			controller : 'XZQYearReportController',
			templateUrl: getBasePath()+'/sw/ReportData/ReportYearXZQ.do'
		}).state('ReportXZQ.statistics.dayReport',{
			controller : 'XZQDayReportController',
			templateUrl: getBasePath()+'/sw/ReportData/ReportDayXZQ.do'
		});
		
		$stateProvider.state("AlarmInfo", {
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					template: ''
				},
				'model': {
					controller : 'StationSearchController',
					templateUrl: getBasePath()+'/WasteGas/onlineMonitor/StationSearchPanel.do?sessionId='+sessionId
				},
				'panel': {
					templateUrl: getBasePath()+'/common/command/ui-view.do?sessionId='+sessionId
				}
			}
        }).state('AlarmInfo.main',{
        	controller : 'AlarmInfoController',
			templateUrl: getBasePath()+'/WasteGas/Alarm/AlarmInfoMain.do?sessionId='+sessionId
		}).state('AlarmInfo.alarmProcess',{
			params:{fromState:''},
			controller : 'DataAnormalController',
			templateUrl: getBasePath()+'/WasteGas/operationManager/DataAnormal.do?sessionId='+sessionId
		});
		//设备资产管理
		$stateProvider.state('DeviceManager',{
			views:{
				'nav': {
					controller : 'misFirstRouterCtrl',
					template: ''
				},
				'model': {
					controller : 'StationSearchController',
					templateUrl: getBasePath()+'/sw/onlineMonitor/StationSearchPanel.do'
				},
				'panel': {
					templateUrl: getBasePath()+'/common/command/ui-view.do'
				}
			}
		}).state('DeviceManager.main',{
			controller: 'DeviceManagerController',
			templateUrl: getBasePath()+'/common/DeviceManager/DeviceManager.do',
			params:{stationType:''}
		}).state('DeviceManager.deviceRepair',{
			params:{fromState:'',stationType:''},
			controller : 'FailureRepairController',
			templateUrl: getBasePath()+'/common/operationManager/FailureRepair.do'
		});
		
		//数据分析
		$stateProvider.state('DataAnalysis',{
			views: {
				'model': {
					controller : 'StationListController',
					templateUrl: getBasePath()+'/sw/DataAnalysis/ReportSearchList.do'
				},
				'panel': {
					controller : 'misFirstRouterCtrl',
					templateUrl: getBasePath()+'/sw/DataAnalysis/main/Main.do'
				},
				'nav': {
					controller : 'DataAnalysisNavController',
					templateUrl: getBasePath()+'/sw/DataAnalysis/thirdNav/SectionNav.do'
				}
			}
		}).state("DataAnalysis.section_month_trend", {
			controller : 'DataAnalysisTrendController',
			templateUrl: getBasePath()+'/sw/DataAnalysis/main/Trend.do'
        }).state("DataAnalysis.section_year_trend", {
        	controller : 'DataAnalysisTrendController',	
			templateUrl: getBasePath()+'/sw/DataAnalysis/main/Trend.do'
        }).state("DataAnalysis.section_month_to_month", {
        	controller : 'DataAnalysisX2XController',
			templateUrl: getBasePath()+'/sw/DataAnalysis/main/XToX.do'
        }).state("DataAnalysis.section_quarter_to_quarter", {
        	controller : 'DataAnalysisX2XController',
			templateUrl: getBasePath()+'/sw/DataAnalysis/main/XToX.do'
        }).state("DataAnalysis.section_year_to_year", {
        	controller : 'DataAnalysisX2XController',
			templateUrl: getBasePath()+'/sw/DataAnalysis/main/XToX.do'
        });
		
		//运维管理
		$stateProvider.state('operationManager',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					template: ''
				},
				'model': {
					controller : 'StationSearchController',
					templateUrl: getBasePath()+'/WasteGas/onlineMonitor/StationSearchPanel.do?sessionId='+sessionId
				},
				'panel': {
					templateUrl: getBasePath()+'/common/command/ui-view.do?sessionId='+sessionId
				}
			}
		}).state("operationManager.TaskQuery", {
			module:'water.apps.WasteGas.operationManage.OperationManagerController',
			controller : 'TaskQueryController',
			templateUrl: getBasePath()+'/WasteGas/operationManager/TaskQuery.do'
        }).state("operationManager.TaskQuery.StandardSubstance", {
			controller : 'StandardSubstanceController',
			templateUrl: getBasePath()+'/WasteGas/operationManager/StandardSubstance.do'
        }).state("operationManager.TaskQuery.StandardVerification", {
			controller : 'StandardVerificationController',
			templateUrl: getBasePath()+'/WasteGas/operationManager/StandardVerification.do'
        }).state("operationManager.TaskQuery.FailureRepair", {
			controller : 'FailureRepairController',
			templateUrl: getBasePath()+'/WasteGas/operationManager/FailureRepair.do'
        }).state("operationManager.TaskQuery.MaterialReplace", {
			controller : 'MaterialReplaceController',
			templateUrl: getBasePath()+'/WasteGas/operationManager/MaterialReplace.do'
        }).state("operationManager.TaskQuery.SampleComparison", {
			controller : 'SampleComparisonController',
			templateUrl: getBasePath()+'/WasteGas/operationManager/SampleComparison.do'
        }).state("operationManager.TaskQuery.ExceedComparison", {
			controller : 'ExceedComparisonController',
			templateUrl: getBasePath()+'/WasteGas/operationManager/ExceedComparison.do'
        }).state("operationManager.TaskQuery.DailyInspection", {
			controller : 'DailyInspectionController',
			templateUrl: getBasePath()+'/WasteGas/operationManager/DailyInspection.do'
        }).state("operationManager.TaskQuery.PeriodicalMaintainance", {
			controller : 'PeriodicalMaintainanceController',
			templateUrl: getBasePath()+'/WasteGas/operationManager/PeriodicalMaintainance.do'
        }).state("operationManager.TaskQuery.SiteExamine", {
			controller : 'SiteExamineController',
			templateUrl: getBasePath()+'/WasteGas/operationManager/SiteExamine.do'
        }).state("operationManager.TaskQuery.RealDataAnormal", {
			controller : 'RealDataAnormalController',
			templateUrl: getBasePath()+'/WasteGas/operationManager/RealDataAnormal.do'
        }).state("operationManager.TaskQuery.DataAnormal", {
			controller : 'DataAnormalController',
			templateUrl: getBasePath()+'/WasteGas/operationManager/DataAnormal.do'
        }).state('operationManager.TaskQuery.ArtificialMonitor', {
			controller : 'ArtificialMonitorController',
			templateUrl: getBasePath()+'/WasteGas/operationManager/ArtificialMonitor.do'
        }).state("operationManager.TaskQuery.SupplyWaterDailyInspection",{
        	controller : 'SupplyWaterDailyInspectionController',
			templateUrl: getBasePath()+'/WasteGas/operationManager/SupplyWaterDailyInspection.do'
        }).state("operationManager.TaskQuery.SupplyWaterPeriodicalMaintainance", {
			controller : 'SupplyWaterPeriodicalMaintainanceController',
			templateUrl: getBasePath()+'/WasteGas/operationManager/SupplyWaterPeriodicalMaintainance.do'
        }).state("operationManager.TaskQuery.blank", {
			templateUrl: getBasePath()+'/WasteGas/operationManager/blank.do'
        });
		
		//系统管理
		$stateProvider.state('xtgl_base',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/BaseNav.do'
				},
				'model': {
					templateUrl: getBasePath()+'/common/xtgl/safe/user_search.do'
				},
				'panel': {
					controller : 'misLastRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/safe/user.do'
				}
			}
		});
		//安卓版本控制
		$stateProvider.state('xtgl_android_version',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/BaseNav.do'
				},
				'model': {
					controller : 'AndroidVersionController',
					templateUrl: getBasePath()+'/common/xtgl/android/VersionSearch.do'
				},
				'panel': {
					controller : 'AndroidVersionController',
					templateUrl: getBasePath()+'/common/xtgl/android/VersionList.do'
				}
			}
		});
		$stateProvider.state('operation_station_group',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/OperationNav.do'
				},
				'model': {
					controller : 'GroupStationSearController',
					templateUrl: getBasePath()+'/common/xtgl/operationConfig/group_sation_search.do'
				},
				'panel': {
					controller : 'GroupStationListController',
					templateUrl: getBasePath()+'/common/xtgl/operationConfig/group_station_list.do'
				}
			}
		});
		$stateProvider.state('operation_station_job',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/OperationNav.do'
				},
				'model': {
					controller : 'StationJobSearchController',
					templateUrl: getBasePath()+'/common/xtgl/operationConfig/station_job_search.do'
				},
				'panel': {
					controller : 'StationJobListController',
					templateUrl: getBasePath()+'/common/xtgl/operationConfig/station_job_list.do'
				}
			}
		});
		//运营单位
		$stateProvider.state('operation_unit_list',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/OperationNav.do'
				},
				'model': {
					controller : 'YydwSearchController',
					templateUrl: getBasePath()+'/common/xtgl/operationConfig/operation_unit_search.do'
				},
				'panel': {
					controller : 'YydwSearchController',
					templateUrl: getBasePath()+'/common/xtgl/operationConfig/operation_unit_list.do'
				}
			}
		});
		$stateProvider.state('xtgl_operation',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/OperationNav.do'
				},
				'model': {
					controller : 'GroupStationSearController',
					templateUrl: getBasePath()+'/common/xtgl/operationConfig/group_sation_search.do'
				},
				'panel': {
					controller : 'GroupStationListController',
					templateUrl: getBasePath()+'/common/xtgl/operationConfig/group_station_list.do'
				}
			}
		});
		$stateProvider.state('xtgl_gis_config',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/MapNav.do'
				},
				'model': {
					templateUrl: getBasePath()+'/common/xtgl/gis/config_search.do'
				},
				'panel': {
					controller : 'misLastRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/gis/config.do'
				}
			}
		});
		$stateProvider.state('xtgl_gis_layer',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/MapNav.do'
				},
				'model': {
					templateUrl: getBasePath()+'/common/xtgl/gis/layer_search.do'
				},
				'panel': {
					controller : 'misLastRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/gis/layer.do'
				}
			}
		});
		$stateProvider.state('xtgl_forms_table',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/BaseNav.do'
				},
				'model': {
					templateUrl: getBasePath()+'/common/xtgl/forms/table_para.do'
				},
				'panel': {
					controller : 'misLastRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/forms/table.do'
				}
			}
		});
		$stateProvider.state('xtgl_safe_org',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/BaseNav.do'
				},
				'model': {
					templateUrl: getBasePath()+'/common/xtgl/safe/org_search.do'
				},
				'panel': {
					controller : 'misLastRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/safe/org.do'
				}
			}
		});
		$stateProvider.state('xtgl_safe_user',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/BaseNav.do'
				},
				'model': {
					templateUrl: getBasePath()+'/common/xtgl/safe/user_search.do'
				},
				'panel': {
					controller : 'misLastRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/safe/user.do'
				}
			}
		});
		$stateProvider.state('xtgl_safe_function',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					template: ''
				},
				'model': {
					templateUrl: getBasePath()+'/common/xtgl/safe/function_search.do'
				},
				'panel': {
					controller : 'misLastRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/safe/function.do'
				}
			}
		});
		$stateProvider.state('xtgl_safe_data',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					template: ''
				},
				'model': {
					templateUrl: getBasePath()+'/common/xtgl/safe/data_search.do'
				},
				'panel': {
					controller : 'misLastRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/safe/data.do'
				}
			}
		});
		$stateProvider.state('xtgl_safe_log',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					template: ''
				},
				'model': {
					templateUrl: getBasePath()+'/common/xtgl/safe/log_search.do'
				},
				'panel': {
					controller : 'misLastRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/safe/log.do'
				}
			}
		});
		$stateProvider.state('xtgl_safe_role',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					template: ''
				},
				'model': {
					templateUrl: getBasePath()+'/common/xtgl/safe/role_search.do'
				},
				'panel': {
					controller : 'misLastRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/safe/role.do'
				}
			}
		});
		$stateProvider.state('xtgl_safe_domain',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/BaseNav.do'
				},
				'model': {
					templateUrl: getBasePath()+'/common/xtgl/safe/domain_search.do'
				},
				'panel': {
					controller : 'misLastRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/safe/domain.do'
				}
			}
		});
		//运维组设置
		$stateProvider.state('operation_group',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/OperationNav.do'
				},
				'model': {
					controller:"GroupSearchController",
					templateUrl: getBasePath()+'/common/xtgl/operationConfig/group_search.do'
				},
				'panel': {
					templateUrl: getBasePath()+'/common/xtgl/operationConfig/group_main.do'
				}
			}
		}).state("operation_group.group_list", {
			controller : 'GroupListController',
			templateUrl: getBasePath()+'/common/xtgl/operationConfig/group_list.do'
        });
		
		//运维事件设置
		$stateProvider.state('operation_job',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/OperationNav.do'
				},
				'model': {
					controller : 'JobConfigController',
					templateUrl: getBasePath()+'/common/xtgl/operationConfig/job_search.do'
				},
				'panel': {
					controller : 'JobConfigController',
					templateUrl: getBasePath()+'/common/xtgl/operationConfig/job_list.do'
				}
			}
		});
		//运维事件参数设置
		$stateProvider.state('operation_param_job',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					templateUrl: getBasePath()+'/common/xtgl/OperationNav.do'
				},
				'model': {
					controller : 'ParamJobConfigController',
					templateUrl: getBasePath()+'/common/xtgl/operationConfig/param_job_search.do'
				},
				'panel': {
					controller : 'ParamJobConfigController',
					templateUrl: getBasePath()+'/common/xtgl/operationConfig/param_job_list.do'
				}
			}
		});
		
		
		//数据有效性审核历史记录
		$stateProvider.state('DataValidationHistory',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					template:''
				},
				'model': {
					controller : 'WsclcSearchController',
					templateUrl: getBasePath()+'/common/DataValidation/DataValidationWsclcSearchPanel.do'
				},
				'panel': {
					controller : 'OperationHistoryController',
					templateUrl: getBasePath()+'/common/DataValidation/HistoryList.do'
				}
			}
		});
		
		//远程控制
		$stateProvider.state('remoteControl',{
			views: {
				'nav': {
					controller : 'misFirstRouterCtrl',
					template: ''
				},
				'model': {
					controller : 'StationSearchController',
					templateUrl: getBasePath()+'/sw/onlineMonitor/StationSearchPanel.do'
				},
				'panel': {
					templateUrl: getBasePath()+'/common/remoteControl/main.do'
				}
			}
		}).state("remoteControl.commonManager", {
			controller : 'commonManagerController',
			templateUrl: getBasePath()+'/common/remoteControl/commonManager.do'
        }).state("remoteControl.remoteControl",{
        	controller : 'remoteControlController',
			templateUrl: getBasePath()+'/common/remoteControl/remoteControl.do'
        }).state("remoteControl.log",{
        	controller : 'sysLogController',
			templateUrl: getBasePath()+'/common/remoteControl/sysLog.do'
        }).state("remoteControl.emergencyAndException",{
        	controller : 'EmergencyAndExceptionController',
			templateUrl: getBasePath()+'/common/remoteControl/EmergencyExceptionControl.do'
        });
		//数据传输有效率统计
		 $stateProvider.state('DataTransValidate',{
				views: {
					'nav': {
						controller : 'misFirstRouterCtrl',
						template:''
					},
					'model': {
						templateUrl: getBasePath()+'/WasteGas/ReportData/ReportSearchList_singleStation.do'
					},
					'panel': {
						templateUrl: getBasePath()+'/WasteGas/command/StatisticsMain.do'
					}
				}
			}).state('DataTransValidate.Statistics',{
				controller : 'ValidationMonitorDataStatisticsController',
				module:'water.apps.WasteGas.dataTransValidation.DataValidationController',
				templateUrl: getBasePath()+'/WasteGas/command/MonitorDataValidation.do'
			}).state('DataTransValidate.Check',{
				controller : 'ValidationMonitorDataCheckController',
				templateUrl: getBasePath()+'/ws/command/MonitorDataValidationCheck.do'
			});
	});
	
	wdp.config(function($httpProvider) {
	    $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
	    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
	 
	    // Override $http service's default transformRequest
	    $httpProvider.defaults.transformRequest = [function(data) {
	        /**
	         * The workhorse; converts an object to x-www-form-urlencoded serialization.
	         * @param {Object} obj
	         * @return {String}
	         */
	        var param = function(obj) {
	            var query = '';
	            var name, value, fullSubName, subName, subValue, innerObj, i;
	 
	            for (name in obj) {
	                value = obj[name];
	 
	                if (value instanceof Array) {
	                    for (i = 0; i < value.length; ++i) {
	                        subValue = value[i];
	                        fullSubName = name + '[' + i + ']';
	                        innerObj = {};
	                        innerObj[fullSubName] = subValue;
	                        query += param(innerObj) + '&';
	                    }
	                } else if (value instanceof Object) {
	                    for (subName in value) {
	                        subValue = value[subName];
	                        fullSubName = name + '[' + subName + ']';
	                        innerObj = {};
	                        innerObj[fullSubName] = subValue;
	                        query += param(innerObj) + '&';
	                    }
	                } else if (value !== undefined && value !== null) {
	                    query += encodeURIComponent(name) + '='
	                            + encodeURIComponent(value) + '&';
	                }
	            }
	 
	            return query.length ? query.substr(0, query.length - 1) : query;
	        };
	 
	        return angular.isObject(data) && String(data) !== '[object File]'
	                ? param(data)
	                : data;
	    }];
	});
	/**
	* 定义WDP默认控制器
	*/
	wdp.controller('wdpCtrl', ['$rootScope', '$scope','$interval', '$gisObject','$itfreer_arcgis_search', '$wdp', '$formObject','OperationStationJobService','$state','$CommonInit','$nav','$waterDataCommon',
		function($rootScope, $scope,$interval, $gisObject,$itfreer_arcgis_search, $wdp,$formObject,OperationStationJobService,$state,$CommonInit){
			$wdp.viewValue={};
			//添加浏览器窗口改变监听
			$wdp.addWindowResizeListener();
			$wdp.widowResizeEventHandler();
			$rootScope.viewValue = $wdp.viewValue;
			$rootScope.BackToMis = function(){
				$wdp.viewValue.showBackToMisBtn = false;
				$formObject.isMIS = true;
			}
			$rootScope.safeApply = function(fn) {
				var phase = this.$root.$$phase;
				if(phase == '$apply' || phase == '$digest') {
				    if(fn && (typeof(fn) === 'function')) {
				    	fn();
				    }
				} else {
					this.$apply(fn);
				}
			};
			
			$CommonInit.init();
			
			$scope.selectMenu = function(menuId){
				if(!($('#'+menuId).hasClass("selected"))){
					$(".zs-menu-list a").removeClass("selected");
					$('#'+menuId).addClass("selected");
				}
			}
			
			//定义实时数据、历史数据、报表，左边栏切换事件
			$scope.$on('dataPramChange', function(event, data) {  
				$scope.$broadcast('dataPramChanged', data);  
		    });
			
			//右边数据区域请求相关参数
			$scope.$on('askDataPramChange', function(event, data) {  
				$scope.$broadcast('askedDataPramChange', data);  
		    });
			
			$rootScope.clearNeighborSearchResult = function(){
				if($itfreer_arcgis_search.neighborLayer){
					$itfreer_arcgis_search.neighborLayer.clear();
				}
				$wdp.viewValue.hasSearchResult = false;
				$gisObject.map.graphics.show();
			}
			
			$scope.isAlarmPlaying = false;
			$scope.popupAlarmInfo = function(){
				OperationStationJobService.postQuery("/Exception/getAlarmInfoList.do",{IS_POPUP_NOT:'1'}).then(function(data){
					if(data && data.data){
						var len = data.data.length;
						if(len==0) return;
						
						var info = data.data[0];
						
						if(toastr.getContainer().length){
							if(toastr.getContainer().find("div[guid='"+info.GUID+"']").length){
								return;
							}
						}
						
						var $toast = toastr.error(getMessage(info),getTitile(),{iconClass:'zs-notice-warn',GUID:info.GUID});
						if(!$toast) return;
						
						play();
						
						if ($toast.find('#btnReadAlarmInfo').length) {
			                $toast.delegate('#btnReadAlarmInfo', 'click', function () {
			                    $toast.remove();
			                    stop();
			                    
			                    var guid = $($toast.find('#btnReadAlarmInfo')[0]).attr('guid');
			                    OperationStationJobService.postQuery("/Data/Update.do",{tableName:'operation_alarm_info',GUID:guid,IS_POPUP:'1'}).then(function(data){
			                    	console.log(data);
			                    });
			                });
			            }
						
						if ($toast.find('#btnAlarmInfoList').length) {
			                $toast.delegate('#btnAlarmInfoList', 'click', function () {
			                	$state.go('AlarmInfo.main');
			                	$scope.selectMenu('menuAlarmInfo1');
			                	
			                    $toast.remove();
			                    stop();
			                    var guid = $($toast.find('#btnReadAlarmInfo')[0]).attr('guid');
			                    OperationStationJobService.postQuery("/Data/Update.do",{tableName:'operation_alarm_info',GUID:guid,IS_POPUP:'1'}).then(function(data){
			                    	console.log(data);
			                    });
			                });
			            }
					}
				});
			};
			
			function play(){
				if($scope.isAlarmPlaying) return;
				if(document.all){
				     try {
				            var wav = document.getElementByIdx_x("MPlayer_Alert");
				            if (wav != null) {
				                wav.Play();
				            }
				        }
				        catch (anError) {
				        }
				}else {
					audio_player.play();
				}
				$scope.isAlarmPlaying = true;
			}
			
			function stop(){
				var hasAlarm = false;
				if($('#toast-container').length){
					if($('#toast-container').find('.toast').length)
						hasAlarm=true;
				}
				if(hasAlarm) return;
				
				if(!+[1,]){
				     try {
				            var wav = document.getElementByIdx_x("MPlayer_Alert");
				            if (wav != null) {
				                wav.Stop();
				            }
				        }
				        catch (anError) {
				        }
				}else {
					audio_player.pause();
					audio_player.currentTime = 0.0;
				}
				$scope.isAlarmPlaying = false;
			}
			//用户名称显示
			$scope.Username="";
			//获取当前登录用户
			$rootScope.currentUser = {};
			OperationStationJobService.postQuery("/Data/getCurrentUser.do",{}).then(function(data){
				$rootScope.currentUser = data;
				if(data){
					$scope.Username=data.C_USEREALNAME;
				}
			});
			
			//退出当前用户
			$scope.loginout=function(){
				OperationStationJobService.postQuery("/login/loginOut.do",{}).then(function(data){
					$.messager.confirm("确认","确定退出当前用户？",function(r){
						if(r){
							window.location.href='/WaterMonitor/sw/login.do';
						}
					});
					
				});
			};
			
			function getMessage(info){
				var s = "<div><div class='content'><table>";
				
				if(info.TYPE=='09'){
					//数采仪掉线，没有参数，阈值，报警值信息
					s+=("<tr><td><strong>异常：</strong></td><td>"+info.TYPE_NAME+"</td></tr>");
				}else{
					s+=("<tr><td><strong>异常：</strong></td><td>"+info.PARAM_NAME + "  "+info.TYPE_NAME+"</td></tr>");
					s+=("<tr><td><strong>报警值：</strong></td><td>"+(info.ALARM_VALUE||'') + "</td></tr>");
					s+=("<tr><td><strong>阈值：</strong></td><td>"+(info.ALARM_THRESHOLD||'') +"</td></tr>");
				}
					
				s+=("<tr><td><strong>站点：</strong></td><td>"+info.STATION_NAME +"</td></tr>");
				s+=("<tr><td><strong>时间：</strong></td><td>"+info.START_TIME +"</td></tr>");
				s+=("</table></div><div class='icon'></div><div class='link'>");
				s+=("<a id='btnReadAlarmInfo' guid='"+info.GUID+"' href='#' class='read'>已读</a>");
				s+=("<a id='btnAlarmInfoList' href='#'>查看报警信息列表</a></div></div>");
				
				return s;
			}
			
			function getTitile(){
				return '<h2>报警信息</h2>';
			}
			
			toastr.options = {
				iconClass:'zs-notice-warn',
				titleClass:'title',
                closeButton: false,
                timeOut:0,
                extendedTimeOut:0,
                newestOnTop: false,
                positionClass: 'toast-bottom-right',
                preventDuplicates: true,
                onclick: null,
                tapToDismiss:false
	        };
			
//			$interval(function(){
//				$scope.popupAlarmInfo();
//			},30000);
		
		$scope.waterTypes = [{name:"工业废气",type:"4"},{name:"工业废水",type:"2"}];
		$scope.waterType = getWaterType();
		$scope.selectWaterType = function(){
			if (!window.location.origin) {
				window.location.origin = window.location.protocol + "//" 
				+ window.location.hostname 
				+ (window.location.port ? ':' + window.location.port : '');
			}
			var origin = window.location.origin;
			var waterType = $scope.waterType;
			if(waterType=='0'){
				//水污染源
				window.location = origin + "/WaterMonitor/sw_ws/index.do";
				//工业污染源，废水
			} else if (waterType =='2') {
				window.location = origin + "/WaterMonitor/WasteWater/index.do";
			} else if (waterType =='4') {
				window.location = origin + "/WaterMonitor/WasteGas/index.do";
			}
			else{
				//地表水站
				window.location = origin + "/WaterMonitor/sw/index.do";
			}
		}
		//获取当前登录用户
		$rootScope.currentUser = {};
		OperationStationJobService.postQuery("/Data/getCurrentUser.do",{}).then(function(data){
			$rootScope.currentUser = data;
		});
		$rootScope.imgShow=function(url){
	        var src = getHostBase() + firstImgUrl(url);
	        $("#bigimg").attr("src", src);
	        $("<img/>").attr("src", src).load(function(){
	            var windowW = $(window).width();
	            var windowH = $(window).height();
	            var realWidth = this.width;
	            var realHeight = this.height;
	            var imgWidth, imgHeight;
	            var scale = 0.8;
	             
	            if(realHeight>windowH*scale) {
	                imgHeight = windowH*scale;
	                imgWidth = imgHeight/realHeight*realWidth;
	                if(imgWidth>windowW*scale) {
	                    imgWidth = windowW*scale;
	                }
	            } else if(realWidth>windowW*scale) {
	                imgWidth = windowW*scale;
	                imgHeight = imgWidth/realWidth*realHeight;
	            } else {
	                imgWidth = realWidth;
	                imgHeight = realHeight;
	            }
	            $("#bigimg").css("width",imgWidth);
	             
	            var w = (windowW-imgWidth)/2;
	            var h = (windowH-imgHeight)/2;
	            $("#innerdiv").css({"top":h, "left":w});
	            $("#outerdiv").fadeIn("fast");
	        });
	    };
		function firstImgUrl(url){
			if(url.indexOf("|") > 0)
			{
				 var arr = url.split("|");
				 return String(arr[arr.length-1].toString().split(":")[0]);
		    }
			 else{
				 var arr = url.split(":");
				return String(arr[0]);
			 }
		};
	}
	]);
}(window, angular));